/*
 * $Id$
 */
package corejs.parser;

import corejs.stmt.Statement;
import corejs.stmt.VarDeclaration;
import corejs.expr.AssignmentExpr;
import corejs.expr.Expression;
import corejs.expr.NameExpr;
import corejs.expr.SequenceExpr;
import corejs.stmt.Block;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author pengyu
 */
public class VarParser implements StatementParser {

   @Override
   public Statement statement(final PrattParser parser) {
      final Block currentBlock = parser.currentBlock();

      final Expression expr = parser.expr();
      if (expr instanceof SequenceExpr) {
         return sequence((SequenceExpr) expr, currentBlock);
      } 
      else if (expr instanceof NameExpr) {
         return new VarDeclaration(((NameExpr)expr).name());
      } 
      else if (expr instanceof AssignmentExpr) {
         return new VarDeclaration(processAssignment(currentBlock, expr));
      }
      return null;
   }

   private VarDeclaration sequence(final SequenceExpr seq,
                                   final Block currentBlock) {
      final List<String> names = new ArrayList<String>();
      for (final Expression ex : seq) {
         if (ex instanceof NameExpr) {
            names.add(((NameExpr) ex).name());
         } else if (ex instanceof AssignmentExpr) {
            names.add(processAssignment(currentBlock, ex));
         }
      }
      return new VarDeclaration(names);
   }

   private String processAssignment(final Block currentBlock, 
                                    final Expression expr) {
      currentBlock.addStatement(expr);
      return ((NameExpr)((AssignmentExpr)expr).left()).name();

   }
}
